/**
*	打开证件采集
*/
function papersClick(value){
		if (typeof currentStream !== 'undefined') {
		  stopMediaTracks(currentStream);
		}
		var videoConstraints = {};
		//var value = $('input:radio[name="cameras"]:checked').val();
		if (value === '' || value === '1'  || value === '2') {
			videoConstraints.facingMode = 'environment';
		} else {
			videoConstraints.deviceId = { exact: value};
		}
		const constraints = {
		  video: videoConstraints,
		  audio: false
		};
		
		navigator.mediaDevices
		.getUserMedia(constraints)
		.then(stream => {
			currentStream = stream;
			papersVideo.srcObject = stream;
			return navigator.mediaDevices.enumerateDevices();
		})

	.catch(error => {
	  console.error(error);
	});
}

/**
*	证件拍照
*/
function papersCameClick() {
  //获得Canvas对象
  let video = document.getElementById("papersVideo");
  let canvas = document.getElementById("papersImg");
  let img =  document.getElementById("img");
  let ctx = canvas.getContext('2d');
  ctx.drawImage(video, 0, 0, 348, 261);
  canvas.style.display = 'none';
  img.style.display='';
  var dataURL = canvas.toDataURL("image/png");
  img.src=dataURL;
  img.style.transform = 'rotate('+papersCurrent+'deg)';
}

var papersCurrent =0;
function papersRotateLeft(){
	papersCurrent = (papersCurrent+90)%360;
	var papersVideo = document.getElementById("papersVideo");
	var papersVideo = document.getElementById("papersVideo");
	papersVideo.style.transform = 'rotate('+papersCurrent+'deg)';
}
/**function papersRotateRight(){
	papersCurrent = (papersCurrent-90)%360;
	var papersVideo = document.getElementById("papersVideo");
	papersVideo.style.transform = 'rotate('+papersCurrent+'deg)';
}*/
function fresh(){
	if(location.href.indexOf("?reload=true")<0){
		location.href+="?reload=true";
		alert("初次使用摄像头需要授权，授权后请关闭浏览器重启！");
	}
}
//var papersSelect;

function getDevice(){
	 let count = 1;
	//papersSelect = document.getElementById("papersSelect");
	navigator.mediaDevices.enumerateDevices()
	.then(function(devices) {
		
	  devices.forEach(function(device) {
		if("videoinput" == device.kind){
			const label = device.label || `Camera ${count++}`;  // 本地执行时返回值为空
			console.log(device.deviceId);
			if(label == "Camera 1"){
				papersClick("");  // 初次使用授权
				setTimeout(fresh(),2000);
			}
			if("Master camera (2017:0010)" ==  label || "Master camera" ==  label){
				let paperRadio = document.getElementById("papersCamera");
				paperRadio.value = device.deviceId;
				paperRadio.checked="checked";
			}
			if( "Slave camera (2017:0011)" ==  label || "Slave camera" ==  label){
				document.getElementById("figureCamera").value = device.deviceId;
			}
			
		}
	  });
	  
	})
	.catch(function(err) {
	  console.log(err.name + ": " + err.message);
	});
}

let currentStream;
function stopMediaTracks(stream) {
  stream.getTracks().forEach(track => {
    track.stop();
  });
}